package com.wangsd.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.util.UriUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * ApplicationUtils : 程序工具类，提供大量的便捷方法
 */
public class BaseUtils {

    /**
     * url 编码
     *
     * @param source url
     * @return 编码后的url
     */
    public static String encodeURL(String source) {
        return UriUtils.encode(source, "utf-8");
    }

    /**
     * 获取证书文件
     * @param name
     * @return
     */
    /*public static InputStream getCertByName(String name) {
        String fileName = name.substring(name.indexOf("."));
        if (".p12".equals(fileName)) { //微信
            fileName = "cert/wechat/" + name;
        }else if (".crt".equals(fileName)) {//支付宝
            fileName = "cert/alipay/" + name;
        }else {
            throw new BusinessException("证书文件名称错误:" + name);
        }
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        InputStream inputStream;
        try {
            inputStream =classPathResource.getInputStream();
        } catch (IOException e) {
            throw new BusinessException("读取证书文件错误:" + name);
        }
        return inputStream;
    }*/

    /**
     * 获取证书文件
     *
     * @param name
     * @return
     */
    public static String getPathCertByName(String name) {
        String fileName = name.substring(name.indexOf("."));
        if (".p12".equals(fileName)) { //微信
            fileName = "cert/wechat/" + name;
        } else if (".crt".equals(fileName)) {//支付宝
            fileName = "cert/alipay/" + name;
        } else {
            throw new RuntimeException("证书文件名称错误:" + name);
        }
        ClassPathResource classPathResource = new ClassPathResource(fileName);
        try {
            return classPathResource.getFile().getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回长度为【strLength】的随机数，在前面补0
     *
     * @param strLength 长度
     * @return 随机数
     */
    public static String getFixLengthString(int strLength) {

        Random rm = new Random();

        // 获得随机数
        double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
        System.out.println(pross);
        // 将获得的获得随机数转化为字符串
        String fixLengthString = String.valueOf(pross);

        // 返回固定的长度的随机数
        return fixLengthString.substring(1, strLength + 1);
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param strxml
     * @return
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) {
        if (null == strxml || "".equals(strxml)) {
            return null;
        }
        /*=============  !!!!注意，修复了微信官方反馈的漏洞，更新于2018-10-16  ===========*/
        try {
            Map<String, String> data = new HashMap<String, String>();
            // TODO 在这里更换
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            documentBuilderFactory.setXIncludeAware(false);
            documentBuilderFactory.setExpandEntityReferences(false);

            InputStream stream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
           ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getPathCertByName("apiclient_zykj.p12"));
//        String returnXml = "<xml>"
//                + "<return_code><![CDATA[SUCCESS]]></return_code>"
//                + "<return_msg><![CDATA[OK]]></return_msg>"
//                + "</xml> ";
//        System.out.println(returnXml.replace("SUCCESS", "success"));
    }

}
